﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class FishGenerator : MonoBehaviour {

	public GameObject player;
	[HideInInspector]
	public List<GameObject> woodList;
	public GameObject fishPrefab;
	public GameObject bubblePrefab;
	public GameObject waveGroup;
	private float GenerateDelayTime;
	private float currentTime;
	void Start () {
		currentTime = 0f;
		GenerateDelayTime = Random.Range (3f, 5f);
		woodList = GameObject.Find ("WoodSpawn").GetComponent<WoodSpawn> ().instan;
	}
	
	void Update () {
		if (currentTime < GenerateDelayTime) {
			currentTime += Time.deltaTime;
		}
		if (currentTime >= GenerateDelayTime) {
			GenerateFish ();
			GenerateDelayTime = Random.Range (3f, 5f);
			currentTime = 0f;
		}
	}

	public void GenerateFish(){
		float minX = Camera.main.ScreenToWorldPoint (new Vector3(100, 0, 0)).x;
		float centerX = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width / 2f, 0, 0)).x;
		float maxX = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, 0)).x;
		if (woodList.Count <= 0) {
			float v = Random.value;
			if (v <= 0.3) {
				float positionX = Random.Range (minX, centerX);
				newFish (positionX);
			} else {
				float positionX = Random.Range (centerX, maxX);
				newFish (positionX);
			}
		} else {
			int tryCount = 3;
			int currentCount = 0;
			while (currentCount < tryCount) {
				float positionX = 0f;
				float v = Random.value;
				if (v <= 0.3) {
					positionX = Random.Range (minX, centerX);
				} else {
					positionX = Random.Range (centerX, maxX);
				}
				bool needReset = false;
				for (var i = 0; i < woodList.Count; i++) {
					var wood = woodList [i];
					var wid = wood.GetComponentInChildren<SpriteRenderer> ().sprite.bounds.size.x;

					if (wood.transform.position.x - wid / 2 <= positionX && wood.transform.position.x + wid / 2 >= positionX) {
						needReset = true;
						break;
					}
				}
				if (!needReset) {
					newFish (positionX);
					break;
				}
				currentCount += 1;
			}
		}
	}

	public void newFish(float x){
		Vector3 minPos = Camera.main.ScreenToWorldPoint (new Vector3 (0, 0, 0));
		Vector3 maxPos = Camera.main.ScreenToWorldPoint (new Vector3 (Screen.width, 0, 0));
		GameObject go = Instantiate (fishPrefab, transform);
		var fish = go.GetComponent<Fish> ();
		go.transform.parent = transform;
		float y = waveGroup.GetComponent<Groups>().getY (x);
		fish.transform.position = new Vector3 (x, minPos.y -fish.GetComponent<SpriteRenderer>().sprite.bounds.size.x, 0);
		var bubble = GenerateBubble(x, y-1.5f);
		bubble.fish = fish;
	}

	public Bubble GenerateBubble(float x, float y){
		GameObject go = Instantiate (bubblePrefab, transform);
		var bubble = go.GetComponent<Bubble> ();
		bubble.transform.position = new Vector3 (x, y, 0);
		bubble.transform.parent = transform;
		bubble.GetComponent<GameAnimation>().Play ();
		return bubble;
	}
}
